package com.java4.connection;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.junit.Test;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author jingjintao
 * @date 2021/6/11 - 0:07
 **/
public class DBCPTest {
    //方式一
    @Test
    public void test() throws SQLException {
        //创建了DBCP的数据库连接池
        BasicDataSource bds = new BasicDataSource();
        //设置基本信息
        bds.setDriverClassName("com.mysql.cj.jdbc.Driver");
        bds.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true");
        bds.setUsername("root");
        bds.setPassword("root");

        //还可以设置其他涉及数据库连接池管理的相关属性：
        bds.setInitialSize(10);
        bds.setMaxActive(10);

        final Connection conn = bds.getConnection();
        System.out.println(conn);
    }

    //方式二：推荐：使用配置文件
    @Test
    public void testGetConnection1() throws Exception {
        Properties prop = new Properties();
        //方式1
//        final InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("dbcp.properties");
        //方式二
        final FileInputStream is = new FileInputStream("src/dbcp.properties");
        prop.load(is);
        final DataSource source = BasicDataSourceFactory.createDataSource(prop);

        final Connection conn = source.getConnection();
        System.out.println(conn);
    }
}
